package com.itheima.case2.web;

import com.itheima.case2.pojo.User;
import com.itheima.case2.serviceiterface.UserService;
import com.itheima.case2.utils.BaseController;
import com.itheima.case2.utils.BeansFactory;
import com.itheima.case2.vo.PageBean;
import com.itheima.case2.vo.Result;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//http://localhost:8080/user?methodName=findAllUsers
@WebServlet("/user")
public class User3Servlet extends BaseServlet {
    //删除
    public void deleteUserById(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("deleteUserById...");
    }
    //添加用户信息
    public void addUser(HttpServletRequest request, HttpServletResponse response) {
        //获取请求数据

        try {
            User user = BaseController.parseJSON2Object(request, User.class);
            //创建业务层对象
            UserService userService = (UserService) BeansFactory.getSingleBean("userService");
            //调用业务层方法：（添加）新增用户
            userService.addUser(user);
            //返回响应到浏览器
            //4.重定向到分页查询的servlet
            response.sendRedirect("/user?methodName=findAllUsersByPage&curPage=1&pageSize=5");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //修改用户的信息
    public void updateUser(HttpServletRequest request, HttpServletResponse response) {
        //在该方法体中处理请求和响应
        //获取请求参数
//        Map<String, String[]> parameterMap = request.getParameterMap();
//        //创建User2，将获取的请求参数封装到User2对象中
//        User user = new User();
        //通过工具类进行封装
        try {
        /*
                请求参数updateUser属于json格式，那么我们直接提交json,但是后台需要
               使用request.getInputStream()流获取，不能request.getParameter()或者request.getParameterMap()
         */
            //System.out.println(request.getParameter("username"));null
            /*
                public static  <T> T parseJSON2Object(HttpServletRequest request, Class<T> tClass) throws IOException{
                    // 把json格式的表单数据直接转成T类型的对象
                    return JSON.parseObject(request.getInputStream(),tClass);
                }
                使用JSON.parseObject将json数据封装到实体类对象中，要求json的key必须和实体类的成员变量名一致
             */
            User user = BaseController.parseJSON2Object(request, User.class);
            //2.创建业务层对象
            UserService userService = (UserService) BeansFactory.getSingleBean("userService");
            //3.使用业务层对象调用更新方法
            userService.updateUserById(user);
            //4.重定向到分页查询的servlet
            response.sendRedirect("/user?methodName=findAllUsersByPage&curPage=1&pageSize=5");


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //查询
    public void findAllUsers(HttpServletRequest request, HttpServletResponse response) {
    }

    //分页查询
    //其实就需要BaseServlet和User3Servlet即可，剩下的几个关于用户的servlet都是为了演示怎么通过反射简化代码的书写
    //改写我们以前实现一个功能就需要写一个servelt，这样我们给每一个角色模块创建一个servlet就行了
    public void findAllUsersByPage(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, IllegalAccessException, InstantiationException {

        //获取方法名参数
        String methodName = request.getParameter("methodName");
        //获取当前页数
        String curPage = request.getParameter("curPage");
        //获取每一页的数据量
        String pageSize = request.getParameter("pageSize");

        //创建service层对象
        //UserServiceImpl userService = new UserServiceImpl();
        //不再使用new对象，从配置文件加载new对象-------使用反射+配置文件实现
        //加载beans.properties配置文件
//        ResourceBundle beans = ResourceBundle.getBundle("beans");
//        String classPath = beans.getString("userService");
//        //获取实现类的Class对象
//        Class clazz = Class.forName(classPath);
//        //创建对象
//        UserService userService = (UserService) clazz.newInstance();

        //使用工厂类直接获取业务层对象
        UserService userService = (UserService) BeansFactory.getBeans("userService");

        //使用service层对象，调用分页查询的方法，传递当前页面和每一页的数据量
         PageBean<User> pb = userService.findAllUsersByPage(Integer.parseInt(curPage), Integer.parseInt(pageSize));
        //将获取的数据响应给浏览器
        //4.响应数据给前端
        //BaseController.printResult(response,new Result(true,"分页查询成功",pb));"
        try {
            BaseController.printResult(response,new Result(true,"分页查询成功",pb));
        } catch (IOException e) {
            e.printStackTrace();
            try {
                //查询失败，响应给前端
                BaseController.printResult(response,new Result(false,"分页查询失败"));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }


    }
}
